All files / controllers NotificationController.js

0% Statements 0/286
0% Branches 0/127
0% Functions 0/19
0% Lines 0/244

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Notification Controller
 * Manages email and WhatsApp notification settings, templates, and sending
 * 
 * @module controllers/NotificationController
 */
 
const BaseController = require('./BaseController');
const { pool } = require('../config/database');
const { logger } = require('../config/logger');
const nodemailer = require('nodemailer');
 
class NotificationController extends BaseController {
  // ==================== EMAIL NOTIFICATIONS ====================
  
  /**
   * Get email settings
   */
  static async getEmailSettings(req, res) {
    try {
      const [settings] = await pool.execute(
        'SELECT * FROM email_notification_settings WHERE id = 1'
      );
 
      if (settings[0]) {
        delete settings[0].smtp_password;
      }
 
      return res.json({
        success: true,
        data: settings[0] || null
      });
    } catch (error) {
      logger.error('Get email settings error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Update email settings
   */
  static async updateEmailSettings(req, res) {
    try {
      const { smtp_host, smtp_port, smtp_secure, smtp_user, smtp_password, from_email, from_name, enabled } = req.body;
      const [existing] = await pool.execute('SELECT id FROM email_notification_settings WHERE id = 1');
 
      if (existing.length === 0) {
        await pool.execute(
          `INSERT INTO email_notification_settings 
           (smtp_host, smtp_port, smtp_secure, smtp_user, smtp_password, from_email, from_name, enabled) 
           VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
          [smtp_host, smtp_port, smtp_secure, smtp_user, smtp_password, from_email, from_name, enabled]
        );
      } else {
        const updates = [];
        const values = [];
 
        if (smtp_host !== undefined) { updates.push('smtp_host = ?'); values.push(smtp_host); }
        if (smtp_port !== undefined) { updates.push('smtp_port = ?'); values.push(smtp_port); }
        if (smtp_secure !== undefined) { updates.push('smtp_secure = ?'); values.push(smtp_secure); }
        if (smtp_user !== undefined) { updates.push('smtp_user = ?'); values.push(smtp_user); }
        if (smtp_password) { updates.push('smtp_password = ?'); values.push(smtp_password); }
        if (from_email !== undefined) { updates.push('from_email = ?'); values.push(from_email); }
        if (from_name !== undefined) { updates.push('from_name = ?'); values.push(from_name); }
        if (enabled !== undefined) { updates.push('enabled = ?'); values.push(enabled); }
 
        if (updates.length > 0) {
          values.push(1);
          await pool.execute(`UPDATE email_notification_settings SET ${updates.join(', ')} WHERE id = ?`, values);
        }
      }
 
      logger.info('Email settings updated');
      return res.json({ success: true, message: 'Email settings updated successfully' });
    } catch (error) {
      logger.error('Update email settings error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Test email connection
   */
  static async testEmailConnection(req, res) {
    try {
      const { smtp_host, smtp_port, smtp_secure, smtp_user, smtp_password, from_email, test_recipient } = req.body;
 
      if (!test_recipient) {
        return res.status(400).json({ success: false, message: 'Test recipient email is required' });
      }
 
      if (!smtp_host || !smtp_port || !smtp_user || !smtp_password) {
        return res.status(400).json({ success: false, message: 'SMTP configuration is incomplete' });
      }
 
      // Create transporter with more robust settings
      const transporterConfig = {
        host: smtp_host,
        port: parseInt(smtp_port),
        secure: smtp_secure === true || smtp_secure === 'true' || parseInt(smtp_port) === 465,
        auth: { 
          user: smtp_user, 
          pass: smtp_password 
        },
        // Connection timeout settings
        connectionTimeout: 10000, // 10 seconds
        greetingTimeout: 10000,
        socketTimeout: 15000,
        // TLS settings for better compatibility
        tls: {
          rejectUnauthorized: false, // Allow self-signed certificates
          minVersion: 'TLSv1.2'
        }
      };
 
      // For port 587, use STARTTLS
      if (parseInt(smtp_port) === 587) {
        transporterConfig.secure = false;
        transporterConfig.requireTLS = true;
      }
 
      logger.info('Testing email connection', { 
        host: smtp_host, 
        port: smtp_port, 
        secure: transporterConfig.secure,
        user: smtp_user 
      });
 
      const transporter = nodemailer.createTransport(transporterConfig);
 
      // Verify connection first
      try {
        await transporter.verify();
        logger.info('SMTP connection verified successfully');
      } catch (verifyError) {
        logger.error('SMTP verification failed', { error: verifyError.message });
        return res.status(500).json({ 
          success: false, 
          message: `SMTP connection failed: ${verifyError.message}. Please check your SMTP settings.` 
        });
      }
 
      // Send test email
      await transporter.sendMail({
        from: from_email || smtp_user,
        to: test_recipient,
        subject: 'Test Email - Misayan SaaS',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h1 style="color: #00a149;">✅ Test Successful!</h1>
            <p>Your email configuration is working correctly.</p>
            <hr style="border: 1px solid #eee;">
            <p style="color: #666; font-size: 12px;">
              Sent from: ${smtp_host}:${smtp_port}<br>
              Time: ${new Date().toISOString()}
            </p>
          </div>
        `
      });
 
      return res.json({ success: true, message: 'Test email sent successfully' });
    } catch (error) {
      logger.error('Test email error', { error: error.message, stack: error.stack });
      
      // Provide more helpful error messages
      let userMessage = error.message;
      if (error.code === 'ECONNRESET') {
        userMessage = 'Connection was reset by the server. This may be due to firewall settings, incorrect port, or the SMTP server rejecting the connection.';
      } else if (error.code === 'ECONNREFUSED') {
        userMessage = 'Connection refused. Please verify the SMTP host and port are correct.';
      } else if (error.code === 'ETIMEDOUT') {
        userMessage = 'Connection timed out. The SMTP server may be unreachable or blocked by firewall.';
      } else if (error.code === 'EAUTH' || error.message.includes('auth')) {
        userMessage = 'Authentication failed. Please check your username and password.';
      }
      
      return res.status(500).json({ success: false, message: `Email test failed: ${userMessage}` });
    }
  }
 
  /**
   * Get email templates
   */
  static async getEmailTemplates(req, res) {
    try {
      const { category } = req.query;
      let query = 'SELECT * FROM email_notification_templates';
      const params = [];
 
      if (category) {
        query += ' WHERE category = ?';
        params.push(category);
      }
      query += ' ORDER BY category, template_name';
 
      const [templates] = await pool.execute(query, params);
      return res.json({ success: true, data: templates });
    } catch (error) {
      logger.error('Get email templates error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Update email template
   */
  static async updateEmailTemplate(req, res) {
    try {
      const { id } = req.params;
      const { subject, body, html_body, enabled } = req.body;
      const updates = [];
      const values = [];
 
      if (subject !== undefined) { updates.push('subject = ?'); values.push(subject); }
      if (body !== undefined) { updates.push('body = ?'); values.push(body); }
      if (html_body !== undefined) { updates.push('html_body = ?'); values.push(html_body); }
      if (enabled !== undefined) { updates.push('enabled = ?'); values.push(enabled); }
 
      if (updates.length > 0) {
        values.push(id);
        await pool.execute(`UPDATE email_notification_templates SET ${updates.join(', ')} WHERE id = ?`, values);
      }
 
      logger.info(`Email template updated: ${id}`);
      return res.json({ success: true, message: 'Template updated successfully' });
    } catch (error) {
      logger.error('Update email template error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
 
  // ==================== WHATSAPP NOTIFICATIONS ====================
 
  /**
   * Get WhatsApp connection status
   */
  static async getWhatsAppStatus(req, res) {
    try {
      const [settings] = await pool.execute('SELECT * FROM whatsapp_notification_settings WHERE id = 1');
      const setting = settings[0] || { connected: false, enabled: false };
 
      try {
        const { getWhatsAppService } = require('../services/WhatsAppService');
        const io = req.app.get('io');
        const whatsappService = getWhatsAppService(io);
        const tenantId = 0; // Superadmin tenant
        
        if (whatsappService) {
          const status = whatsappService.getStatus(tenantId);
          const qrCode = await whatsappService.getQRCode(tenantId);
          
          logger.info('WhatsApp status check', {
            tenantId,
            hasInstance: !!whatsappService.getInstance(tenantId),
            connected: status.connected,
            initialized: status.initialized,
            hasQR: !!qrCode,
            qrLength: qrCode ? qrCode.length : 0,
            qrPreview: qrCode ? qrCode.substring(0, 50) : null
          });
          
          return res.json({
            success: true,
            data: {
              connected: status.connected || false,
              qrCode: qrCode || null,
              phoneNumber: status.phoneNumber || setting.phone_number,
              lastConnected: setting.last_connected_at,
              enabled: setting.enabled
            }
          });
        }
        
        return res.json({
          success: true,
          data: {
            connected: false,
            qrCode: null,
            phoneNumber: setting.phone_number,
            lastConnected: setting.last_connected_at,
            enabled: setting.enabled
          }
        });
      } catch (wsError) {
        logger.warn('WhatsApp service not available', { error: wsError.message });
        return res.json({
          success: true,
          data: {
            connected: false,
            qrCode: null,
            phoneNumber: setting.phone_number,
            lastConnected: setting.last_connected_at,
            enabled: setting.enabled
          }
        });
      }
    } catch (error) {
      logger.error('Get WhatsApp status error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Initialize WhatsApp connection
   */
  static async initWhatsApp(req, res) {
    try {
      const { getWhatsAppService } = require('../services/WhatsAppService');
      const io = req.app.get('io');
      const whatsappService = getWhatsAppService(io);
      
      // Use tenant ID 0 for superadmin notifications
      const tenantId = 0; // Superadmin tenant
      
      if (!whatsappService) {
        return res.status(500).json({ success: false, message: 'WhatsApp service not initialized' });
      }
      
      await whatsappService.initializeTenant(tenantId);
      logger.info('WhatsApp initialization started for superadmin notifications');
      return res.json({ success: true, message: 'WhatsApp initialization started. Please scan the QR code.' });
    } catch (error) {
      logger.error('Init WhatsApp error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Disconnect WhatsApp
   */
  static async disconnectWhatsApp(req, res) {
    try {
      const { getWhatsAppService } = require('../services/WhatsAppService');
      const io = req.app.get('io');
      const whatsappService = getWhatsAppService(io);
      const tenantId = 0; // Superadmin uses tenant 0
      
      if (!whatsappService) {
        return res.status(500).json({ success: false, message: 'WhatsApp service not initialized' });
      }
      
      await whatsappService.disconnect(tenantId);
      await pool.execute('UPDATE whatsapp_notification_settings SET connected = FALSE WHERE id = 1');
      logger.info('WhatsApp disconnected for superadmin notifications');
      return res.json({ success: true, message: 'WhatsApp disconnected successfully' });
    } catch (error) {
      logger.error('Disconnect WhatsApp error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Get WhatsApp settings
   */
  static async getWhatsAppSettings(req, res) {
    try {
      const [settings] = await pool.execute('SELECT * FROM whatsapp_notification_settings WHERE id = 1');
      return res.json({ success: true, data: settings[0] || null });
    } catch (error) {
      logger.error('Get WhatsApp settings error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Update WhatsApp settings
   */
  static async updateWhatsAppSettings(req, res) {
    try {
      const { phone_number, session_name, enabled } = req.body;
      const [existing] = await pool.execute('SELECT id FROM whatsapp_notification_settings WHERE id = 1');
 
      if (existing.length === 0) {
        await pool.execute(
          `INSERT INTO whatsapp_notification_settings (phone_number, session_name, enabled) VALUES (?, ?, ?)`,
          [phone_number, session_name || 'superadmin_notifications', enabled]
        );
      } else {
        const updates = [];
        const values = [];
        if (phone_number !== undefined) { updates.push('phone_number = ?'); values.push(phone_number); }
        if (session_name !== undefined) { updates.push('session_name = ?'); values.push(session_name); }
        if (enabled !== undefined) { updates.push('enabled = ?'); values.push(enabled); }
 
        if (updates.length > 0) {
          values.push(1);
          await pool.execute(`UPDATE whatsapp_notification_settings SET ${updates.join(', ')} WHERE id = ?`, values);
        }
      }
 
      logger.info('WhatsApp settings updated');
      return res.json({ success: true, message: 'WhatsApp settings updated successfully' });
    } catch (error) {
      logger.error('Update WhatsApp settings error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Get WhatsApp templates
   */
  static async getWhatsAppTemplates(req, res) {
    try {
      const { category } = req.query;
      let query = 'SELECT * FROM whatsapp_notification_templates';
      const params = [];
 
      if (category) {
        query += ' WHERE category = ?';
        params.push(category);
      }
      query += ' ORDER BY category, template_name';
 
      const [templates] = await pool.execute(query, params);
      return res.json({ success: true, data: templates });
    } catch (error) {
      logger.error('Get WhatsApp templates error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Update WhatsApp template
   */
  static async updateWhatsAppTemplate(req, res) {
    try {
      const { id } = req.params;
      const { message, enabled } = req.body;
      const updates = [];
      const values = [];
 
      if (message !== undefined) { updates.push('message = ?'); values.push(message); }
      if (enabled !== undefined) { updates.push('enabled = ?'); values.push(enabled); }
 
      if (updates.length > 0) {
        values.push(id);
        await pool.execute(`UPDATE whatsapp_notification_templates SET ${updates.join(', ')} WHERE id = ?`, values);
      }
 
      logger.info(`WhatsApp template updated: ${id}`);
      return res.json({ success: true, message: 'Template updated successfully' });
    } catch (error) {
      logger.error('Update WhatsApp template error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
 
  // ==================== PLAN EXPIRATION SETTINGS ====================
 
  /**
   * Get plan expiration reminder settings
   */
  static async getExpirationSettings(req, res) {
    try {
      const [settings] = await pool.execute('SELECT * FROM plan_expiration_settings WHERE id = 1');
      return res.json({
        success: true,
        data: settings[0] || {
          days_before_1: 7, days_before_2: 3, days_before_3: 1, days_before_4: 0,
          days_after_1: 1, days_after_2: 3, days_after_3: 7, enabled: true
        }
      });
    } catch (error) {
      logger.error('Get expiration settings error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Update plan expiration reminder settings
   */
  static async updateExpirationSettings(req, res) {
    try {
      const { days_before_1, days_before_2, days_before_3, days_before_4,
              days_after_1, days_after_2, days_after_3, enabled } = req.body;
 
      const [existing] = await pool.execute('SELECT id FROM plan_expiration_settings WHERE id = 1');
 
      if (existing.length === 0) {
        await pool.execute(
          `INSERT INTO plan_expiration_settings 
           (days_before_1, days_before_2, days_before_3, days_before_4, days_after_1, days_after_2, days_after_3, enabled) 
           VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
          [days_before_1, days_before_2, days_before_3, days_before_4, days_after_1, days_after_2, days_after_3, enabled]
        );
      } else {
        await pool.execute(
          `UPDATE plan_expiration_settings SET 
           days_before_1 = ?, days_before_2 = ?, days_before_3 = ?, days_before_4 = ?,
           days_after_1 = ?, days_after_2 = ?, days_after_3 = ?, enabled = ? WHERE id = 1`,
          [days_before_1, days_before_2, days_before_3, days_before_4, days_after_1, days_after_2, days_after_3, enabled]
        );
      }
 
      logger.info('Plan expiration settings updated');
      return res.json({ success: true, message: 'Expiration settings updated successfully' });
    } catch (error) {
      logger.error('Update expiration settings error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  // ==================== NOTIFICATION LOGS ====================
 
  /**
   * Get notification logs
   */
  static async getNotificationLogs(req, res) {
    try {
      const { type, status, page = 1, limit = 50 } = req.query;
      const { page: pageNum, limit: limitNum, offset } = BaseController.validatePagination(page, limit);
 
      let query = 'SELECT * FROM notification_logs WHERE 1=1';
      const params = [];
 
      if (type) { query += ' AND notification_type = ?'; params.push(type); }
      if (status) { query += ' AND status = ?'; params.push(status); }
 
      query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
      params.push(limitNum, offset);
 
      const [logs] = await pool.execute(query, params);
 
      let countQuery = 'SELECT COUNT(*) as total FROM notification_logs WHERE 1=1';
      const countParams = [];
      if (type) { countQuery += ' AND notification_type = ?'; countParams.push(type); }
      if (status) { countQuery += ' AND status = ?'; countParams.push(status); }
 
      const [countResult] = await pool.execute(countQuery, countParams);
 
      return res.json({
        success: true,
        data: logs,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total: countResult[0].total,
          totalPages: Math.ceil(countResult[0].total / limitNum)
        }
      });
    } catch (error) {
      logger.error('Get notification logs error', { error: error.message });
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Send test WhatsApp notification
   */
  static async sendTestWhatsApp(req, res) {
    try {
      const { phone_number, message } = req.body;
      if (!phone_number || !message) {
        return res.status(400).json({ success: false, message: 'Phone number and message are required' });
      }
 
      const { getWhatsAppService } = require('../services/WhatsAppService');
      const io = req.app.get('io');
      const whatsappService = getWhatsAppService(io);
      
      if (!whatsappService) {
        return res.status(500).json({ success: false, message: 'WhatsApp service not initialized' });
      }
      
      const result = await whatsappService.sendMessage(0, phone_number, message);
      
      if (!result.success) {
        throw new Error(result.error || 'Failed to send message');
      }
 
      await pool.execute(
        `INSERT INTO notification_logs (notification_type, template_key, recipient, message, status, sent_at)
         VALUES ('whatsapp', 'test', ?, ?, 'sent', NOW())`,
        [phone_number, message]
      );
 
      return res.json({ success: true, message: 'Test message sent successfully' });
    } catch (error) {
      logger.error('Send test WhatsApp error', { error: error.message });
      try {
        await pool.execute(
          `INSERT INTO notification_logs (notification_type, template_key, recipient, message, status, error_message)
           VALUES ('whatsapp', 'test', ?, ?, 'failed', ?)`,
          [req.body.phone_number, req.body.message, error.message]
        );
      } catch (logError) {
        logger.error('Failed to log notification error', { error: logError.message });
      }
      return res.status(500).json({ success: false, message: error.message });
    }
  }
 
  /**
   * Send notification to tenant
   */
  static async sendNotificationToTenant(tenantId, templateKey, type = 'both', customData = {}) {
    try {
      const notificationService = require('../services/NotificationService');
      return await notificationService.sendNotificationToTenant(tenantId, templateKey, type, customData);
    } catch (error) {
      logger.error('Send notification to tenant error', { error: error.message, tenantId });
      throw error;
    }
  }
 
  /**
   * Send email notification using template
   */
  static async sendEmailNotification(recipient, templateKey, variables) {
    const notificationService = require('../services/NotificationService');
    return await notificationService.sendEmailNotification(recipient, templateKey, variables);
  }
 
  /**
   * Send WhatsApp notification using template
   */
  static async sendWhatsAppNotification(recipient, templateKey, variables) {
    const notificationService = require('../services/NotificationService');
    return await notificationService.sendWhatsAppNotification(recipient, templateKey, variables);
  }
}
 
module.exports = NotificationController;